package com.yuand.filter;

import com.yuand.utils.BodyReaderHttpServletRequestWrapper;
import com.yuand.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yuandong
 * @company KB
 * @create 2022-03-24 15:07
 */
@Slf4j
@WebFilter(urlPatterns={"/stu/*"})
public class MyFilter  extends OncePerRequestFilter {

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

		log.info("请求进入过滤器了........");

		//包装HttpServletRequest对象，缓存body数据，再次读取的时候将缓存的值写出,解决HttpServetRequest读取body只能一次的问题
		HttpServletRequest requestWrapper = null;
		if (request instanceof HttpServletRequest) {
			requestWrapper = new BodyReaderHttpServletRequestWrapper(request);
		}

		//获取请求Ip
		String clientIp = HttpUtils.getIpAddrByRequest(request);

		//获取请求路径
		String requestUrl = HttpUtils.getRequestUrl(request);


		//获取请求体中的数据，如果是Get请求 requestBody则为空串
		String requestBody = HttpUtils.getRequestBody(requestWrapper);

		//获取请求路径上拼接的参数
		LinkedHashMap<String, List<String>> params = HttpUtils.getUrlParams(requestWrapper);
	}

}
